package vboot.app.my.demo.main;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vboot.core.common.mvc.service.BaseMainService;
import vboot.core.common.utils.web.XuserUtil;
import vboot.core.module.bpm.proc.cond.BpmProcCond;
import vboot.core.module.bpm.proc.cond.BpmProcCondRepo;
import vboot.core.module.bpm.proc.main.BpmProcMainService;
import vboot.core.module.bpm.proc.main.Zbpm;
import vboot.core.module.bpm.proc.main.Znode;
import vboot.core.common.utils.lang.IdUtils;

import javax.annotation.PostConstruct;
import java.util.Date;

//DEMO主数据服务
@Service
public class MyDemoMainService extends BaseMainService<MyDemoMain> {

    public void insertx(MyDemoMain main) throws Exception {
        main.setState("20");
        main.setId(IdUtils.getUID());
        main.setUptim(new Date());
        if (main.getCrman() == null) {
            main.setCrman(XuserUtil.getUser());
        }
        MyDemoMain dbMain = repo.save(main);
        BpmProcCond cond = new BpmProcCond();
        cond.setId(dbMain.getId());
        Gson gson = new Gson();
        cond.setCond(gson.toJson(dbMain));
        condRepo.saveAndFlush(cond);

        Zbpm zbpm = main.getZbpm();
        zbpm.setModty("app_demo");
        zbpm.setProid(dbMain.getId());
        zbpm.setProna(dbMain.getName());
        zbpm.setHaman(dbMain.getCrman().getId());
        zbpm.setTmpid(dbMain.getProtd());
        Znode znode = procService.start(zbpm);
        if ("NE".equals(znode.getFacno())) {
            dbMain.setState("30");
            super.update(dbMain);
        }
    }

    public void updatex(MyDemoMain main) throws Exception {
        main.setState("20");
        super.update(main);
        BpmProcCond cond = new BpmProcCond();
        cond.setId(main.getId());
        Gson gson = new Gson();
        cond.setCond(gson.toJson(main));
        condRepo.saveAndFlush(cond);

        main.getZbpm().setModty("app_demo");
        if ("pass".equals(main.getZbpm().getOpkey())) {
            Znode znode = procService.handlerPass(main.getZbpm());
            if ("NE".equals(znode.getFacno())) {
                main.setState("30");
                super.update(main);
            }
        } else if ("refuse".equals(main.getZbpm().getOpkey())) {
            if ("N1".equals(main.getZbpm().getTarno())) {
                main.setState("11");
                super.update(main);
            }
            Znode znode = procService.handlerRefuse(main.getZbpm());
        }
    }



    @Autowired
    private BpmProcMainService procService;

    @Autowired
    private BpmProcCondRepo condRepo;

    @Autowired
    private MyDemoMainRepo repo;

    @PostConstruct
    public void initDao() {
        super.setRepo(repo);
    }

}

